import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken(), // 从缓存中读取初始值
  uInfo: {}, // 存储用户基本资料状态
  routes: constantRoutes // 静态路由的数组
}

const mutations = {
  setToken: (state, token) => {
    state.token = token
    // 同步到缓存
    setToken(token)
  },
  removeToken: (state) => {
    // 删除Vuex的token
    state.token = null
    removeToken()
  },
  setuInfo: (state, uInfo) => { // 修改用户信息
    state.uInfo = uInfo
  },
  setRoutes: (state, newRoutes) => {
    state.routes = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
  }
}

const actions = {
  // context上下文，传入参数
  login: async (context, data) => {
    // 调用登录接口
    const token = await login(data)
    // 返回一个token
    context.commit('setToken', token)
  },
  getuInfo: async (context) => { // 获取用户信息
    const result = await getInfo()
    context.commit('setuInfo', result)
    return result
  },
  logout: (context) => {
    context.commit('removeToken') // 删除token
    context.commit('setuInfo', {}) // 设置用户信息为空对象
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true, // 开启命名空间
  state,
  mutations,
  actions
}

